﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Practices.Unity;

namespace ERPStore.Web.Services
{
    public class ValidatorFactory : global::FluentValidation.ValidatorFactoryBase
    {
        private Microsoft.Practices.Unity.IUnityContainer m_Container;
		private static object m_Lock = new object();

        public ValidatorFactory(Microsoft.Practices.Unity.IUnityContainer container)
        {
            m_Container = container;
        }

        public override global::FluentValidation.IValidator CreateInstance(Type validatorType)
        {
			ContainerRegistration registered = null;
			lock (m_Lock)
			{
				var query = from t in m_Container.Registrations
							where t.RegisteredType.FullName == validatorType.FullName
							select t;

				registered = query.SingleOrDefault();
			}

			if (registered != null)
			{
				var validator = m_Container.Resolve(registered.RegisteredType, registered.Name);
				return validator as global::FluentValidation.IValidator;
			}
			return null;
        }
    }
}
